package com.ic.controller;

import com.ic.common.DroolsContainer;
import com.ic.domain.DataChangeNotify;
import com.ic.domain.Device;
import com.ic.service.DeviceService;
import com.ic.service.RuleAction;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/notify")
@Slf4j
public class NotifyController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DroolsContainer droolsContainer;
    @Autowired
    private RuleAction ruleAction;
    @PostMapping("/dataChange")
    public ResponseEntity dataChange(@RequestBody DataChangeNotify notify) {
        Device device = deviceService.findById(notify.getDeviceId());
        if (null == device) throw new IllegalArgumentException("Device not found");
        Map<String, Object> data = notify.getData();
        device.getProperties().forEach(p -> {
            Object val = MapUtils.getObject(data, p.getCode());
            if (null != val) p.setValue(val);
        });
        KieBase kieBase = droolsContainer.getKieBase(device.getAppId());
        KieSession session = kieBase.newKieSession();
        session.setGlobal("ruleAction", ruleAction);
        session.setGlobal("droolsContainer", droolsContainer);
        session.insert(notify);
        session.insert(droolsContainer.getRuleContext());
        session.insert(device);
        session.fireAllRules();
        session.destroy();
        return ResponseEntity.ok().build();
    }
}
